package test10;

import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;

/**
 * 2. 分析以下需求，并用代码实现
 * 1.定义学生类,包含姓名(String name),性别(String gender),年龄(int age)三个属性,生成空参有参构造,set和get方法,toString方法
 * 2.键盘录入6个学员信息(录入格式:张三,男,25),要求有两个相同的信息,将6个学员信息存入到ArrayList集合中
 * 3.将存有6个学员信息的ArrayList集合对象写入到D:\\StudentInfo.txt文件中
 * 4.读取D:\\StudentInfo.txt文件中的ArrayList对象并遍历打印
 * 5.对ArrayList集合中的6个学生对象进行去重,将去重后的结果利用PrintWriter流写入到E:\\StudentInfo.txt文件中(写入格式：张三-男-25)
 */
public class TestDemo02_2 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        int count = 0;
        ArrayList<Student2> student = new ArrayList<Student2>();
        while (count < 6) {
            System.out.println("请输入成员信息： ");
            Scanner sc = new Scanner(System.in);
            String stuString = sc.nextLine();
            String[] stuInfo = stuString.split(",");
            Student2 stu = new Student2(stuInfo[0], stuInfo[1], Integer.parseInt(stuInfo[2]));
            student.add(stu);
            count++;
        }

        writeToFile(student);

        readFromFile(new File("D:\\StudentInfo.txt"));

        //去重:
        ArrayList<Student2> distinct = distinct(student);
        //去重后写入文件：
        printWriteToFile(distinct);

//        System.out.println(student);

        //将集合写入文件中：

    }

    private static void printWriteToFile(ArrayList<Student2> student2) throws IOException {

        PrintWriter pw = new PrintWriter("E:\\StudentInfo.txt");
        for (Student2 student21 : student2) {
            pw.write(student21.getName() + " - " +
                    student21.getGender() + " - " +
                    student21.getAge());
            pw.write("\r\n");
        }
        pw.close();

    }

    public static void writeToFile(ArrayList<Student2> student2) throws IOException {
        FileOutputStream fos = new FileOutputStream("D:\\StudentInfo.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(student2);
        oos.close();
    }

    public static void readFromFile(File file) throws IOException, ClassNotFoundException {
        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Object o = ois.readObject();
        System.out.println(o);
        fis.close();
        ois.close();
    }


    //去重：
    public static ArrayList<Student2> distinct(ArrayList<Student2> student2) {
        for (int i = 0; i < student2.size(); i++) {
            for (int j = i + 1; j < student2.size(); j++) {
                if (student2.get(i).getName().equals(student2.get(j).getName())
                        && student2.get(i).getGender().equals(student2.get(j).getGender())
                        && student2.get(i).getAge() == student2.get(j).getAge()) {
                    student2.remove(i);
                }
            }
        }
        return student2;
    }
}
